import os
import subprocess
import sys


def convert_m4a_to_mp3_ffmpeg(input_file, output_file, bitrate="192k"):
    """
    直接调用ffmpeg将M4A转换为MP3

    Args:
        input_file: 输入的M4A文件路径
        output_file: 输出的MP3文件路径
        bitrate: MP3比特率

    Returns:
        str: 输出文件路径
    """
    if not os.path.exists(input_file):
        raise FileNotFoundError(f"输入文件不存在: {input_file}")

    if output_file is None:
        output_file = os.path.splitext(input_file)[0] + '.mp3'

    # 确保输出目录存在
    output_dir = os.path.dirname(output_file)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)

    try:
        # 构建ffmpeg命令
        cmd = [
            'ffmpeg',
            '-i', input_file,
            '-codec:a', 'libmp3lame',
            '-b:a', bitrate,
            '-y',  # 覆盖输出文件
            output_file
        ]

        print(f"开始转换: {input_file}")

        # 运行ffmpeg命令
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)

        print(f"转换成功: {output_file}")
        return output_file

    except subprocess.CalledProcessError as e:
        print(f"ffmpeg转换失败: {e}")
        if e.stderr:
            print(f"错误信息: {e.stderr}")
        raise
    except FileNotFoundError:
        print("错误: 未找到ffmpeg，请确保已安装ffmpeg并添加到系统PATH")
        raise


input_file = "/home/suke/tangqi/ai_arm_controller/audio_file/1.m4a"
output_file = "/home/suke/tangqi/ai_arm_controller/audio_file/1.mp3"

convert_m4a_to_mp3_ffmpeg(input_file, output_file, bitrate="192k")